<?php
namespace Home\Controller;
use Think\Controller;

use Home\Model\OrderModel;

class OrderController extends CommonController{

  protected $orderModel;

  public function _initialize(){
    parent::_initialize();
    $this->orderModel=new orderModel();
  }
  /**
   * 订单列表
   */
  public function index()
  {
    $this->orders=$this->orderModel->getAllByUid(session('uid'));
    var_dump($this->orders);
    $this->display();
  }

  /**
   * 处理创建订单表单
   *
   * @return json [code ,msg ]
   */
  public function createAction(){

    $order=[];
    $order['amount']=0;
    $foodsModel=M('foods');
    $foodsList=json_decode(I('get.data'));
    $pattern='/\d+/';
    $selectFoods=[];
    foreach ($foodsList as $key => $value) {
      preg_match($pattern,$key, $matches);
      $food=$foodsModel->find($matches[0]);
      $food['nums']=$value;
      $order['amount']+=$food['price']*$value;
      array_push($selectFoods,$food);
    }
    $order['foods']=json_encode($selectFoods);
    $order['uid']=session('uid');
    $order['mid']=session('mid');
    if(M('order')->add($order))
      $rs=['code'=>1,'msg'=>'下单成功!'];
    else $rs=['code'=>0,'msg'=>'下单失败!'];
    $this->ajaxReturn($rs);
  }
}
